package Java_Concurrency_in_Practice.c3_4_2;

import java.math.BigInteger;

/** c_2_3_1 */
public class CachedFactorizer {
	
	private BigInteger lastNumber;
	private BigInteger[] lastFactors;
	private long hits;
	private long cacheHits;
	
	public synchronized long getHits() {
		return hits;
	}
	
	public synchronized double getCacheHitsRatio() {
		return (double)cacheHits / (double)hits;
	}
	
	public BigInteger[] service(BigInteger i) {
		BigInteger[] factors = null;
		
		synchronized (this) {
			++hits;
			if (i.equals(lastNumber)) {
				++cacheHits;
				factors = lastFactors.clone();
			}
			
		}
		
		if (factors == null) {
			factors = factor(i);
			synchronized (this) {
				lastNumber = i;
				lastFactors = factors.clone();
			}
		}
		
		return factors;
	}

	private BigInteger[] factor(BigInteger i) {
		return null;
	}

}
